package com.campus.schedule.timer;

import com.campus.common.enums.OrderStatusEnum;
import com.campus.schedule.entity.Order;
import com.campus.schedule.service.OrderService;
import com.campus.schedule.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 订单超时处理服务
 */
@Service
@Slf4j
public class OrderTimeoutService {

    @Autowired
    private RedisService redisService;
    
    @Autowired
    private OrderService orderService;
    
    private static final String ORDER_TIMEOUT_QUEUE = "order_timeout_queue";
    private static final int TIMEOUT_MINUTES = 15;

    /**
     * 处理超时订单队列
     */
    @Scheduled(fixedDelay = 10000) // 每10秒检查一次
    public void processTimeoutOrders() {
        try {
            long currentTime = System.currentTimeMillis();
            
            // 获取到期的任务，每次最多处理100个
            Set<String> expiredTasks = redisService.getExpiredTasks(ORDER_TIMEOUT_QUEUE, currentTime, 100);
            
            if (!expiredTasks.isEmpty()) {
                log.info("发现 {} 个到期的订单任务", expiredTasks.size());
                
                for (String orderId : expiredTasks) {
                    processTimeoutOrder(orderId);
                }
                
                // 批量删除已处理的任务
                redisService.removeDelayTasks(ORDER_TIMEOUT_QUEUE, expiredTasks);
                log.info("已处理并删除 {} 个到期任务", expiredTasks.size());
            }
        } catch (Exception e) {
            log.error("处理超时订单队列异常", e);
        }
    }

    /**
     * 处理单个超时订单
     * @param orderId 订单ID
     */
    private void processTimeoutOrder(String orderId) {
        try {
            Order order = orderService.getById(orderId);
            if (order == null) {
                log.warn("订单不存在: {}", orderId);
                return;
            }

            // 只有待付款状态的订单才需要取消
            if (order.getStatus().equals(OrderStatusEnum.PENDING_PAYMENT.getValue())) {
                order.setStatus(OrderStatusEnum.CANCELLED.getValue());
                order.setStatusText(OrderStatusEnum.CANCELLED.getText());
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时未支付，系统自动取消");
                
                orderService.updateById(order);
                log.info("订单 {} 超时未支付，已自动取消", orderId);
            } else {
                log.info("订单 {} 状态为 {}，无需取消", orderId, order.getStatusText());
            }
        } catch (Exception e) {
            log.error("处理超时订单异常: {}", orderId, e);
        }
    }

    /**
     * 兜底方案：每天凌晨1点执行，查询数据库中超时未支付的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨1点执行
    public void cancelTimeoutOrdersFromDatabase() {
        try {
            log.info("开始执行兜底方案：查询数据库中超时未支付的订单");
            
            // 计算15分钟前的时间
            LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(TIMEOUT_MINUTES);
            Date timeoutDate = Date.from(timeoutTime.atZone(ZoneId.systemDefault()).toInstant());
            
            // 查询超时未支付的订单
            List<Order> timeoutOrders = orderService.findTimeoutUnpaidOrders(timeoutDate);
            
            for (Order order : timeoutOrders) {
                order.setStatus(OrderStatusEnum.CANCELLED.getValue());
                order.setStatusText(OrderStatusEnum.CANCELLED.getText());
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时未支付，系统自动取消（兜底处理）");
                
                orderService.updateById(order);
                log.info("兜底处理：订单 {} 超时未支付，已自动取消", order.getId());
            }
            
            log.info("兜底方案执行完成，共处理 {} 个超时订单", timeoutOrders.size());
        } catch (Exception e) {
            log.error("兜底方案执行异常", e);
        }
    }
}